package org.goldfish.demo.apicall.analysis.code.di;

import javafx.fxml.FXMLLoader;
import org.goldfish.demo.apicall.analysis.code.CodeAnalyzeApplication;
import org.goldfish.demo.apicall.analysis.code.CodeAnalyzeController;

import java.net.URL;

public class SpringFXMLLoader extends FXMLLoader {
    public SpringFXMLLoader(String location) {
        this(getResourceURL(location));
    }

    public SpringFXMLLoader(Class<?> resourceBaseClass, String location) {
        this(getResourceURL(resourceBaseClass, location));
    }

    public SpringFXMLLoader(URL location) {
        super(location);
        setControllerFactory(CodeAnalyzeApplication.getSpringContext()::getBean);
    }
    
    private static URL getResourceURL(String location) {
        // 处理绝对路径（以/开头）
        if (location.startsWith("/")) {
            return SpringFXMLLoader.class.getResource(location);
        }
        
        // 处理相对路径
        URL resource = CodeAnalyzeController.class.getResource(location);
        // 如果没有找到，尝试在相同包中查找
        if (resource == null) {
            resource = CodeAnalyzeController.class.getResource("/org/goldfish/demo/apicall/analysis/code/" + location);
        }
        return resource;
    }
    
    private static URL getResourceURL(Class<?> resourceBaseClass, String location) {
        return resourceBaseClass.getResource(location);
    }
}